<template>
  <div>
    <n-card :header-style="{padding: '10px 10px 0px 10px'}" :content-style="{padding: '5px 5px 5px 5px'}">
    <n-grid>
      <n-grid-item :span="24">
        <n-card :content-style="{padding: '5px 5px 5px 5px'}" :bordered="false">
          <n-space justify="space-between" style="margin-bottom: 5px;">
            <n-text type="success">共{{storyBoardList.length}}个分镜</n-text>
            <n-space>
              <n-text v-if="storyBoardList.length==0"><n-text type="error">您还未划分分镜,请划分分镜</n-text></n-text>
              <n-button type="primary" @click="diffModal = true">分镜划分 </n-button>
            </n-space>
          </n-space>
          <n-data-table
              :columns="storyBoardColumns"
              :data="storyBoardList"
              :style="{ height: `${clientHeight - (layoutHeaderHeight  + tabsHeight + 300)}px` }"
              flex-height
          />
        </n-card>
      </n-grid-item>
    </n-grid>
    </n-card>
  </div>

  <n-modal v-model:show="diffModal" :closable="true">
    <n-card
        style="width: 1600px"
        title="分镜划分  请勿修改文案，保持分镜与原文案数量一致！ "
        :bordered="false"
        size="huge"
        role="dialog"
        aria-modal="true"
    >
      <n-space justify="space-between" style="padding-bottom: 10px;">
        <n-space>
          <n-input-group>
            <n-button type="primary">每</n-button>
            <n-input-number style="width: 50px" placeholder="" :show-button="false" v-model:value="autoStoryBoardLines"></n-input-number>
            <n-button type="primary">行文案为一个分镜</n-button>
          </n-input-group>
          <n-button style="margin-left: 5px;" type="info" @click="autoStoryBoard">自动分镜</n-button>
        </n-space>

        <n-space>
          <n-text type="warning">{{info}}</n-text>
          <n-button style="margin-left: 100px;" type="primary" @click="saveStoryBoards">保存分镜</n-button>
        </n-space>

      </n-space>
      <n-grid x-gap="5">
        <n-grid-item :span="8">
          <n-h6>原文案</n-h6>
          <n-input
              type="textarea"
              style="height: 600px"
              v-model:value="originSrtContent"
              :readonly="true">
          </n-input>
        </n-grid-item>
        <n-grid-item :span="8">
          <n-h6>分镜文案</n-h6>
          <n-input
              type="textarea"
              style="height: 600px"
              @update:value="srtContentChange"
              v-model:value="srtContent">
          </n-input>
        </n-grid-item>
        <n-grid-item :span="8">
          <n-h6>提示</n-h6>
          <Diff
              mode="split"
              theme="dark"
              language="plaintext"
              :prev="originSrtContent"
              :current="srtContent"
              :folding="true"
              :input-delay="0"
              :virtual-scroll="{ height: 580, lineMinHeight: 24, delay: 100 }"
          />
        </n-grid-item>
      </n-grid>
    </n-card>
  </n-modal>
</template>

<script lang="ts" setup>
import {storeToRefs} from "pinia";
import {useSystemStore} from "@/store/modules/useSystemStore";
import {h, onMounted, ref} from "vue";
import {storyController} from "@/api/story/story.api";
import {Diff} from "vue-diff";
import {NInput} from "naive-ui";
const info = ref('')

const {
  clientHeight,
  layoutHeaderHeight,
  darkTheme,
  tabsHeight
} = storeToRefs(useSystemStore());

const noPickerLoading = ref(false)
const videoNoPickerList = ref([])
const originSrtContent = ref('')
const srtContent = ref('')
const diffModal = ref(false)
const storyBoardList = ref([])
const autoStoryBoardLines = ref(2)

const props = defineProps({
  storyId: {
    type: String,
    required: true
  }
})

onMounted(() => {
  getVideoTextNoPicker()
  getStoryBoardList()
})

const getVideoTextNoPicker = () => {
  noPickerLoading.value = true
  storyController.getVoiceTextNoPicker(props.storyId).then(res => {
    if (res.code === 200) {
      videoNoPickerList.value = res.data
      srtContent.value = videoNoPickerList.value.map(item => {
        return item.videoText
      }).join('\n')
      originSrtContent.value = videoNoPickerList.value.map(item => {
        return item.videoText
      }).join('\n')
    }
  }).finally(() => {
    noPickerLoading.value = false
  })
}

const getStoryBoardList = () =>{
  storyController.getStoryBoardList(props.storyId).then(res => {
    if (res.code === 200) {
      storyBoardList.value = res.data.records
      // srtContent.value = ''
      // for (let i = 0; i < storyBoardList.value.length; i++) {
      //   for (let j = 0; j < storyBoardList.value[i].sentenceList.length; j++) {
      //
      //     if (i != storyBoardList.value.length -1 ){
      //       srtContent.value += storyBoardList.value[i].sentenceList[j].content + '\n'
      //       if (j===storyBoardList.value[i].sentenceList.length-1) {
      //         srtContent.value += '\n'
      //       }
      //     }else {
      //       if (j < storyBoardList.value[i].sentenceList.length - 1) {
      //         srtContent.value += storyBoardList.value[i].sentenceList[j].content + '\n'
      //       } else {
      //         srtContent.value += storyBoardList.value[i].sentenceList[j].content
      //       }
      //     }
      //   }
      // }
    }
  })
}

const saveStoryBoards = () => {
  if (srtContent.value.length === 0) {
    window.$message.warning('请选择文案')
    return
  }
  let storyBoardText = []
  let lines = srtContent.value.split(/\r?\n/);
  let board = ''
  lines.forEach(line => {
    if (line.trim() === '') {
      if (board.trim().length > 0) {
        storyBoardText.push(board)
        board = ''
      }
    } else {
      board += line + '\n'
    }
  })
  storyBoardText.push(board)
  if (checkStoryBoardOK(storyBoardText)) {
    // 判断是否插入分镜
    window.$dialog.warning({
      title: "提示",
      content: "您共分" + storyBoardText.length + "个分镜，是否保存?",
      positiveText: "确定",
      negativeText: "取消",
      onPositiveClick: () => {
        initStoryBoard(storyBoardText)
      }
    })
  }
}



const initStoryBoard = (storyBoardText:[]) => {
  let initParam = []
  let num = 0;
  for (let i = 0; i < storyBoardText.length; i++) {
    let singlePram = []
    let lines = storyBoardText[i].split('\n');
    lines = lines.filter(line => line.trim() !== '')
    for (let j = 0; j < lines.length; j++) {
      singlePram.push(num)
      num++
    }
    initParam.push(singlePram)
  }
  const param = {
    storyId: props.storyId,
    storyBoardInfos: initParam
  }
  storyController.initStoryBoards(param).then(res => {
    if (res.code === 200) {
      window.$message.success('保存成功')
      getVideoTextNoPicker()
      getStoryBoardList()
      diffModal.value = false
    }
  })
}


const srtContentChange = (value: string) => {
  srtContent.value = value
  let storyBoardText = []
  let lines = srtContent.value.split(/\r?\n/);
  let board = ''
  lines.forEach(line => {
    if (line.trim() === '') {
      if (board.trim().length > 0) {
        storyBoardText.push(board)
        board = ''
      }
    } else {
      board += line + '\n'
    }
  })
  storyBoardText.push(board)
  checkStoryBoardOK(storyBoardText)


}
const checkStoryBoardOK = (storyBoardText: []) => {
  let totalLines = 0
  storyBoardText.forEach(item => {
    let lines = item.split('\n');
    lines = lines.filter(line => line.trim() !== '')
    totalLines += lines.length
  })
  let originLines = originSrtContent.value.split('\n').filter(line => line.trim() !== '').length
  if (totalLines !== originLines) {
    info.value = '分镜与原文案数量不一致,分镜'+totalLines+'行,原文案'+originLines+'行'
  }else {
    info.value = ''
  }

  return totalLines === originLines
}

const storyBoardColumns = [
  {
    title: '序号',
    key: 'orderNum',
    align: 'center',
    width: 80
  },{
    title: '文案',
    key: 'content',

    render: (row: any) => {
      let content = ''
      row.sentenceList.forEach((item: any, index: number) => {
        content +=  item.content + '\n'
      })
      return h(NInput, {
        value: content,
        readonly: true,
        type: 'textarea',
        style: 'height: 100px'
      })
    }
  }
]


const autoStoryBoard = () =>{
  if (videoNoPickerList.value.length === 0) {
    window.$message.warning('没有文案')
    return
  }

  srtContent.value = ''
  srtContent.value = videoNoPickerList.value.map((item,index) => {
    if (index % autoStoryBoardLines.value === 0 && index > 0){
      return '\n' + item.videoText
    }
    return item.videoText
  }).join('\n')

}
</script>
